package sync

import (
	"encoding/json"
	"gitee.com/dreamwood/ez-go/ez"
	"github.com/nsqio/go-nsq"
)

const (
	SYNC_PREFIX     = "SYNC"
	TOPIC_CRUD      = "CRUD"
	TOPIC_INIT_NEED = "INIT_NEED"
	TOPIC_INIT_FEED = "INIT_FEED"
	CRUD_C          = "C"
	CRUD_R          = "R" //用不上，暂时预留吧
	CRUD_U          = "U"
	CRUD_D          = "D"
)

type ModelSync struct {
	ServiceName string
	NsqPubAddr  string
	NsqSubAddr  string
	producer    *nsq.Producer
	//consumers   map[string]*nsq.Consumer
}

type MessageHandler struct {
	Handler func(content []byte) error
}

func NewModelSync() *ModelSync {
	MS = new(ModelSync)

	MS.ServiceName = ez.ConfigService.AppId
	MS.NsqPubAddr = ez.ConfigNsq.PubAddr
	MS.NsqSubAddr = ez.ConfigNsq.SubAddr

	MS.InitProducer() //初始化一个producer

	//连接nsq开始监听InitNeed
	InitNeedFeedSub() //创建初始化监听,发布方被动响应的行为。

	return MS
}

var MS *ModelSync

func GetMS() *ModelSync {
	if MS == nil {
		MS = NewModelSync()
	}
	return MS
}

func (ms *ModelSync) GetIdFromInterface(v interface{}) (id int) {
	obj := struct {
		Id int
	}{}
	b, e := json.Marshal(v)
	if e != nil {
		return 0
	}
	e = json.Unmarshal(b, &obj)
	if e != nil {
		return 0
	}
	return obj.Id
}

func (h *MessageHandler) HandleMessage(m *nsq.Message) error {
	if len(m.Body) == 0 {
		// Returning nil will automatically send a FIN command to NSQ to mark the message as processed.
		// In this case, a message with an empty body is simply ignored/discarded.
		return nil
	}
	// do whatever actual message processing is desired
	err := h.Handler(m.Body)
	// Returning a non-nil error will automatically send a REQ command to NSQ to re-queue the message.
	return err
}
